package com.bitcarton.dynamic.datasource.autoconfigure.dialect.xa;

import com.atomikos.jdbc.AtomikosDataSourceBean;
import com.bitcarton.dynamic.datasource.autoconfigure.SqlProperty;
import com.mysql.cj.jdbc.MysqlXADataSource;

import java.sql.SQLException;

/**
 * @author wwd
 */
public class MysqlXAD {

    public static AtomikosDataSourceBean initMysqlXA(SqlProperty sqlProperty) {
        MysqlXADataSource datasource = new MysqlXADataSource();
        datasource.setUrl(sqlProperty.getUrl());
        datasource.setUser(sqlProperty.getUsername());
        datasource.setPassword(sqlProperty.getPassword());
        try {
            datasource.setPinGlobalTxToPhysicalConnection(true);
        } catch (SQLException e) {
            e.printStackTrace();
        }


        //创建atomikos全局事务
        AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();
        xaDataSource.setXaDataSource(datasource);
        xaDataSource.setUniqueResourceName(sqlProperty.getName());
        xaDataSource.setXaDataSourceClassName(sqlProperty.getType());
        xaDataSource.setMinPoolSize(Integer.parseInt(sqlProperty.getMinIdle()));
        xaDataSource.setMaxPoolSize(Integer.parseInt(sqlProperty.getMaxActive()));
        xaDataSource.setPoolSize(Integer.parseInt(sqlProperty.getInitialSize()));

        return xaDataSource;
    }

}
